package com.enba.boot.openfeign.config;

import com.enba.boot.core.base.ShowBootInfo;
import com.enba.boot.openfeign.extend.DefaultRequestTemplateExtend;
import com.enba.boot.openfeign.extend.RequestTemplateExtend;
import com.enba.boot.openfeign.interceptor.FeignRequestInterceptor;
import com.enba.boot.openfeign.properties.OpenFeignProperties;
import feign.Logger;
import feign.RequestInterceptor;
import javax.annotation.PostConstruct;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@ConditionalOnProperty(prefix = "openfeign", name = "enabled", havingValue = "true")
@EnableConfigurationProperties(OpenFeignProperties.class)
@Configuration
public class OpenFeignAutoConfiguration implements ShowBootInfo {

  private final OpenFeignProperties openFeignProperties;

  public OpenFeignAutoConfiguration(OpenFeignProperties openFeignProperties) {
    this.openFeignProperties = openFeignProperties;
  }

  @Bean
  public RequestInterceptor requestInterceptor(
      OpenFeignProperties openFeignProperties, RequestTemplateExtend requestTemplateExtend) {
    return new FeignRequestInterceptor(openFeignProperties, requestTemplateExtend);
  }

  @ConditionalOnMissingBean(RequestTemplateExtend.class)
  @Bean
  public RequestTemplateExtend requestTemplateExtend() {
    return new DefaultRequestTemplateExtend();
  }

  /**
   * 日志级别 <br>
   * NONE：默认，不显示任何日志； <br>
   * BASIC: 仅记录请求方法、URL、响应状态码及执行时间； <br>
   * HEADERS：除了BASIC中定义的信息之外，还有请求头和响应头信息；<br>
   * FULL：除了HEADERS中定义的信息之外，还有请求的正文和响应数据。
   */
  @Bean
  Logger.Level feignLogLevel() {
    String logLevel = openFeignProperties.getLogLevel();
    if (Logger.Level.NONE.name().equals(logLevel)) {
      return Logger.Level.NONE;
    } else if (Logger.Level.BASIC.name().equals(logLevel)) {
      return Logger.Level.BASIC;
    } else if (Logger.Level.HEADERS.name().equals(logLevel)) {
      return Logger.Level.HEADERS;
    }
    return Logger.Level.FULL;
  }

  @PostConstruct
  @Override
  public void showBootInfo() {
    ShowBootInfo.moduleMap.put("enba-boot-starter-openfeign", "enba-boot-starter-openfeign模块集成成功");
  }
}
